package com.common.android.ui.LocalAlbum;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Observable;
import java.util.Observer;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.format.Time;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.common.android.utils.DisplayUtil;
import com.common.android.utils.FileUtils;
import com.common.android.utils.ToastUtils;
import com.common.android.utils.task.progressTask.ProgressTask;
import com.nd.android.u.allcommon.R;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.product.android.business.ProductTypeDef.Product;
import com.product.android.business.config.Configuration;
import com.product.android.ui.activity.HeaderActivity;

public class LocalAlbumMultiSelect extends HeaderActivity implements
		OnItemClickListener, OnClickListener, Observer {

	private static final String TAG = "LocalAlbumMultiSelect";

	protected Button mLeftBtn;

	private LinearLayout mLayoutLocalAlubm;// 本地相册布局
	// 本地相册列表
	private ArrayList<SortedMediaFiles> mListAlbum;
	private ListView m_lvLocalAlbum;
	private AlbumListAdapter m_alAdapter;

	// 头部
	private LinearLayout mllHead;
	private ArrayList<FileInfo> mListRecent;
	private HeadGridViewAdapter mHeadGridViewAdapter;
	private GridView mGridViewRecent;

	// 文件夹中选择
	private LinearLayout mLayoutSelectMore;
	private GridView mGridViewSelectMore;
	private SelectMoreGridViewAdapter mSelectMoreGridViewAdapter;
	private ArrayList<FileInfo> mListSelectMore;

	// 底部
	LinearLayout layoutSelectedPreview;
	private Button m_btnFinish;
	ArrayList<HashMap<String, ImageView>> listFootImageView;
	
	// private ImageFetcher mImgFetcher;
	protected int mScreenWidth;

	private Uri photoUri = null;
	private File mCameraFile = null;

	// 用户选择的照片
	private ArrayList<FileInfo> mlistSelectedFile;

	// 存放Adapter 里的View
	private Map<Integer, View> mMapRecent;
	private Map<Integer, View> mMapSelectMore;

	private ExecutorService mUpdateUI = Executors.newSingleThreadExecutor();

	private static final int MAX_NORMAL_SELECT_COUNT = 9; // 普通图片最多选取9张
	private static final int MAX_RECENT_COUNT = 8; // 最近显示两排，共8张图片
	private static final int FOOT_COLUMN_WIDTH = 40; //底部图片宽度 40dip
	private static final int FOOT_PHOTO_MARING = 4; //底部图片 maring 4dip
	private static final int FOOT_IMAGEVIEW_ID = 0; //底部图片 maring 4dip

	private Intent mIntentService = null;// 搜索系统相片的服务

	private HashMap<String, SortedMediaFiles> mmapAlbumList;
	
	private static final int MAX_NORMAL_IMAGE_SIZE = 5242880 ; // 5M
	
	// -- 外部可配置 -----
	private boolean mIsLimitImageSize = false; // 是否开启图片大小限制
	private int mMaxImageSize = MAX_NORMAL_IMAGE_SIZE; // 图片大小上限，默认5M
	private int mLimitImageSizeHintId = R.string.limit_image_size; // 图片大小限制提示
	private boolean mIsCameraEnable = true; // 拍照按钮是否可用,默认可用
	private int mCameraUnableHintId = R.string.camera_unable_hint; // 拍照按钮不可用提示
	private int mMaxSelectCount = MAX_NORMAL_SELECT_COUNT; // 允许选择的最大上限，默认9张
	
	private int btnFinishBackgroundId;

	private static final String KEY_LIST_SELECT = "list_select";
	
	/** 已选中图片列表 */
	public static final String KEY_IMAGE_PATH = "imagePaths";
	/** 否开启图片大小限制,默认不开启 */
	public static final String KEY_IS_LIMIT_IMAGE_SIZE = "isLimitImageSize";
	/** 图片大小上限，默认5M */
	public static final String KEY_MAX_IMAGE_SIZE = "maxImageSize";
	/** 图片大小限制提示 */
	public static final String KE_LIMIT_IMAGE_SIZE_HINT_ID = "limitImageSizeHintId";
	/** 拍照按钮是否可用,默认可用 */
	public static final String KEY_IS_CAMERA_ENABLE = "isCameraEnable";
	/** 拍照按钮不可用提示 */
	public static final String KEY_CAMERA_UNABLE_HINT_ID = "cameraUnableHintId";
	/** 允许选择的最大上限，默认9张 */
	public static final String KEY_MAX_SELECT_COUNT = "maxSelectCount";
	
	
	public DisplayImageOptions mAvoidOOMOptions = new DisplayImageOptions.Builder()
															.showStubImage(R.drawable.local_image_default)
															.showImageForEmptyUri(R.drawable.local_image_default)
															.showImageOnFail(R.drawable.local_image_default)
															.bitmapConfig(Bitmap.Config.RGB_565)
															.imageScaleType(ImageScaleType.EXACTLY)
															.resetViewBeforeLoading()
															.build();
	
	@SuppressLint("NewApi")
    public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.local_album_multi_select);
		
		listFootImageView = new ArrayList<HashMap<String, ImageView>>();
		mlistSelectedFile = new ArrayList<FileInfo>();
		if (null != savedInstanceState) {
			mlistSelectedFile = savedInstanceState.getParcelableArrayList(KEY_LIST_SELECT);
			mIsLimitImageSize = savedInstanceState.getBoolean(KEY_IS_LIMIT_IMAGE_SIZE);
			mIsCameraEnable = savedInstanceState.getBoolean(KEY_IS_CAMERA_ENABLE);
			mMaxSelectCount = savedInstanceState.getInt(KEY_MAX_SELECT_COUNT);
			mMaxImageSize = savedInstanceState.getInt(KEY_MAX_IMAGE_SIZE);
			mLimitImageSizeHintId = savedInstanceState.getInt(KE_LIMIT_IMAGE_SIZE_HINT_ID);
			mCameraUnableHintId = savedInstanceState.getInt(KEY_CAMERA_UNABLE_HINT_ID);
		} else{
			Intent intent = getIntent();
			ArrayList<String> listImages = null;
			if(intent != null){
				listImages = intent.getStringArrayListExtra(KEY_IMAGE_PATH);
				mIsLimitImageSize = intent.getBooleanExtra(KEY_IS_LIMIT_IMAGE_SIZE, false);
				mIsCameraEnable = intent.getBooleanExtra(KEY_IS_CAMERA_ENABLE, true);
				mMaxSelectCount = intent.getIntExtra(KEY_MAX_SELECT_COUNT, MAX_NORMAL_SELECT_COUNT);
				mMaxImageSize = intent.getIntExtra(KEY_MAX_IMAGE_SIZE, MAX_NORMAL_IMAGE_SIZE);
				mLimitImageSizeHintId = intent.getIntExtra(KE_LIMIT_IMAGE_SIZE_HINT_ID, R.string.limit_image_size);
				mCameraUnableHintId = intent.getIntExtra(KEY_CAMERA_UNABLE_HINT_ID, R.string.camera_unable_hint);
			}
			
			// 构造几个FileInfo以显示在底部
			if (null != listImages && !listImages.isEmpty()) {
				for (String strImagePaht : listImages) {
					FileInfo info = new FileInfo();
					info.mFilePathOrName = strImagePaht;
					mlistSelectedFile.add(info);
				}
			}
		}
		
		initComponent();
		initComponentValue();
		initEvent();
	}
	
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putParcelableArrayList(KEY_LIST_SELECT, mlistSelectedFile);
		outState.putBoolean(KEY_IS_LIMIT_IMAGE_SIZE, mIsLimitImageSize);
		outState.putBoolean(KEY_IS_CAMERA_ENABLE, mIsCameraEnable);
		outState.putInt(KEY_MAX_SELECT_COUNT, mMaxSelectCount);
		outState.putInt(KEY_MAX_IMAGE_SIZE, mMaxImageSize);
		outState.putInt(KE_LIMIT_IMAGE_SIZE_HINT_ID, mLimitImageSizeHintId);
		outState.putInt(KEY_CAMERA_UNABLE_HINT_ID, mCameraUnableHintId);
		
	}

	@SuppressLint("UseSparseArrays")
    @SuppressWarnings("deprecation")
	@Override
    protected void initComponent() {
	    super.initComponent();
	    if (Product.PRODUCT_91XY == Configuration.PRODUCT) {
            btnFinishBackgroundId = R.drawable.bt_header_rights_bg;            
        } else {
            btnFinishBackgroundId = R.drawable.btn_confirm_press;
        }
		
		mScreenWidth = getWindowManager().getDefaultDisplay().getWidth();
		// miScaledWidth = mScreenWidth / 4;
		// mImgFetcher = new ImageFetcher(this, miScaledWidth,
		// BitmapFactory.decodeResource(getResources(),
		// R.drawable.local_image_default));
		mLeftBtn = (Button) findViewById(R.id.header_btn_left);

		mMapRecent = new HashMap<Integer, View>();
		mMapSelectMore = new HashMap<Integer, View>();
		mmapAlbumList = new HashMap<String, SortedMediaFiles>();

		mLayoutLocalAlubm = (LinearLayout) findViewById(R.id.layout_local_album);

		// 列表头部
		mHeadGridViewAdapter = new HeadGridViewAdapter();
		mListRecent = new ArrayList<FileInfo>();
		mllHead = (LinearLayout) View.inflate(this,
				R.layout.local_album_recent_grid, null);
		mGridViewRecent = (GridView) mllHead.findViewById(R.id.grid_recent);
		LinearLayout.LayoutParams linearParams = (LinearLayout.LayoutParams) mGridViewRecent
				.getLayoutParams();
		linearParams.height = mScreenWidth / 2 + 5;
		mGridViewRecent.setLayoutParams(linearParams);

		m_lvLocalAlbum = (ListView) findViewById(R.id.lv_local_album);
		m_lvLocalAlbum.setCacheColorHint(0);

		// 文件夹中选择更多
		mLayoutSelectMore = (LinearLayout) findViewById(R.id.layout_select_more);
		mGridViewSelectMore = (GridView) findViewById(R.id.grid_select_more);
		mSelectMoreGridViewAdapter = new SelectMoreGridViewAdapter();
		mListSelectMore = new ArrayList<FileInfo>();

		// 底部
		layoutSelectedPreview = (LinearLayout)findViewById(R.id.layout_selected_preview);
		m_btnFinish = (Button) this.findViewById(R.id.btn_finish);
	}

	protected void initComponentValue() {
		setActivityTitle(R.string.local_image_lib);
		mGridViewRecent.setAdapter(mHeadGridViewAdapter);

		m_lvLocalAlbum.addHeaderView(mllHead);
		m_alAdapter = new AlbumListAdapter(this);
		m_lvLocalAlbum.setAdapter(m_alAdapter);
		m_lvLocalAlbum.setOnScrollListener(scrollListener);

		mGridViewSelectMore.setAdapter(mSelectMoreGridViewAdapter);
		mGridViewSelectMore.setOnScrollListener(scrollListener);

		for(int i = 0; i < mlistSelectedFile.size(); i++) {
		    addFootPhoto(mlistSelectedFile.get(i).mFilePathOrName);
		}
		    
	}

	protected void initEvent() {
		mLeftBtn.setOnClickListener(this);
		m_btnFinish.setOnClickListener(this);
		m_lvLocalAlbum.setOnItemClickListener(this);
		mGridViewRecent.setOnItemClickListener(this);
		mGridViewSelectMore.setOnItemClickListener(this);
	}

	private void getRecentList(List<SortedMediaFiles> list) {
	    mListRecent.clear();
		if (null == list || list.isEmpty()) {
			return;
		}

		mListRecent.add(new FileInfo()); // 第一个按钮为拍照，增加一个空值
		for (SortedMediaFiles smf : list) {
			if (null != smf) {
				List<FileInfo> listFI = smf.getFilesList();
				if (null != listFI) {
					for (FileInfo fi : listFI) {
						mListRecent.add(fi);
						if (MAX_RECENT_COUNT == mListRecent.size()) {
							mHeadGridViewAdapter.initSelectState();
							return;
						}
					}
				}
			}
		}

		mHeadGridViewAdapter.initSelectState();
	}
	
	/**
	 * 获取选择更多相册图片文件
	 * <br>Created 2014年10月9日 下午8:42:00
	 * @param list 相册图片文件
	 * @author       LuoJianWei
	 */
	private void getSelectMoreList(List<SortedMediaFiles> list) {
	    mListSelectMore.clear();
	    if (null == list || list.isEmpty()) {
	        return;
	    }
	    
	    //当进入某个相册文件夹时，然后把该文件夹都删除时，让它显示空白。
	    if (list.size() != mListAlbum.size()) {
	        return;
        }
	    
	    for (SortedMediaFiles smf : list) {
	        if (null != smf) {
	            List<FileInfo> listFI = smf.getFilesList();
	            if (null != listFI) {
	                for (FileInfo fi : listFI) {
	                    mListSelectMore.add(fi);
	                    if (MAX_RECENT_COUNT == mListSelectMore.size()) {
	                        mSelectMoreGridViewAdapter.initSelectState();
	                        return;
	                    }
	                }
	            }
	        }
	    }
	    
	    mSelectMoreGridViewAdapter.initSelectState();
	}

	private void updateUI() {
		mUpdateUI.submit(new Runnable() {
			@Override
			public void run() {
				final ArrayList<SortedMediaFiles> list = LocalImageController
						.getInstance().getMediaFiles();
				
				getRecentList(list);
				if (View.VISIBLE == mLayoutSelectMore.getVisibility()) {
				    getSelectMoreList(list);
				}
				
				if (null != list) {
                    mListAlbum = list;
                }
				
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						mHeadGridViewAdapter.notifyDataSetChanged();
						m_alAdapter.notifyDataSetChanged();
						mSelectMoreGridViewAdapter.notifyDataSetChanged();
						updateFootPhoto();
						setFinishBtnText();
					}
				});
			}
		});
	}
	
	private void updateFootPhoto() {
	    for (int i = 0; i < listFootImageView.size(); i++) {
            String[] photoPathName1 = listFootImageView.get(i).keySet()
                    .toString().split("\\[");
            String[] photoPathName2 = photoPathName1[1].split("\\]");//去掉相片路径两边的中括号
            File fImage = new File(photoPathName2[0]);
            if (!fImage.exists()) {
                layoutSelectedPreview.removeView(listFootImageView.get(i)
                        .get(photoPathName2[0]));
                listFootImageView.remove(i);
                removeSeletedImg(photoPathName2[0]);
                i--;
            } 
        }
	}
	
	@Override
	public void update(Observable observable, Object data) {
		updateUI();
	}

	@Override
	public void onResume() {
        LocalImageController.getInstance().addObserver(this);
		super.onResume();
	}

	@Override
	protected void onPause() {
		LocalImageController.getInstance().delObserver(this);
		super.onPause();
	}

	@SuppressLint({ "UseSparseArrays", "UseValueOf" })
    private void addFootPhoto(String photoPathName) {
		setFinishBtnText();
		int listSelectedCount = mlistSelectedFile.size();
        if (listSelectedCount > 0) {
            ImageView imageView = new ImageView(this);
            imageView.setId(FOOT_IMAGEVIEW_ID);
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
                    DisplayUtil.dip2px(this, FOOT_COLUMN_WIDTH)
                    , DisplayUtil.dip2px(this, FOOT_COLUMN_WIDTH));
            imageView.setLayoutParams(layoutParams);
            imageView.setTag(photoPathName);
            layoutParams.setMargins(FOOT_PHOTO_MARING, 0, FOOT_PHOTO_MARING, 0);
            imageView.setAdjustViewBounds(true);
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            imageView.setOnClickListener(this);
            
            layoutSelectedPreview.addView(imageView);
            
            HashMap<String, ImageView> mapImageView = new HashMap<String, ImageView>();
            mapImageView.put(photoPathName, imageView);
            listFootImageView.add(mapImageView);
            
            ImageLoader.getInstance().displayImage(FileUtils.LOCAL_FILE_PREFIX 
                    + photoPathName, imageView, mAvoidOOMOptions, null);
        }
	}
	
	/**
	 * 删除底部图片
	 * <br>Created 2014年10月9日 下午9:48:06
	 * @param photoPathName 图片文件名
	 * @author       LuoJianWei
	 */
    private void delFootPhoto(String photoPathName) {
        setFinishBtnText();
        for (int i = 0; i < listFootImageView.size(); i++) {
            HashMap<String, ImageView> map = listFootImageView.get(i);
            if (map.containsKey(photoPathName)) {
                layoutSelectedPreview.removeView(listFootImageView.get(i).get(photoPathName));
                listFootImageView.remove(i);
                break;
            }            
        }
    }
    
	public void setFinishBtnText() {
		if (mlistSelectedFile.isEmpty()) {
			m_btnFinish.setText(getString(R.string.confirm_selection));
			m_btnFinish.setBackgroundResource(R.drawable.btn_confirm_unable);
			m_btnFinish.setEnabled(false);
		} else {
			m_btnFinish.setText(getString(R.string.confirm_selection) + " ("
					+ mlistSelectedFile.size() + "/" + mMaxSelectCount + ")");
			m_btnFinish.setBackgroundResource(btnFinishBackgroundId);
			m_btnFinish.setEnabled(true);
		}
	}

	@Override
	public void onClick(View v) {
		int id = v.getId();
		if (id == R.id.header_btn_left) {
			switchView();
		} else if (id == R.id.btn_finish) {
			doFinish();
		} else if (id == FOOT_IMAGEVIEW_ID){
		    String tag =  (String) v.getTag();
		    disselectFoot(tag);
        }
	}
	
	private void disselectFoot(String strRemovePath) {

        if (View.VISIBLE == mLayoutSelectMore.getVisibility()) {
            // 文件夹中选择更多时，要把被选中的反选
            for (int i = 0; i < mListSelectMore.size(); i++) {
                if (mListSelectMore.get(i).mFilePathOrName
                        .equalsIgnoreCase(strRemovePath)) {
                    mSelectMoreGridViewAdapter.setSelect(i);
                    return;
                }
            }
        } else if (View.GONE == mLayoutSelectMore.getVisibility()) {
            // 文件夹列表中，要把头部中被选中的反选
            for (int i = 1; i < mListRecent.size(); i++) {
                if (mListRecent.get(i).mFilePathOrName
                        .equalsIgnoreCase(strRemovePath)) {
                    mHeadGridViewAdapter.setSelect(i);
                    return;
                }
            }
        }
        
        // 列表没找到的，直接remove
        removeSeletedImg(strRemovePath);
        delFootPhoto(strRemovePath);
	}
	
	private void doFinish() {
		ArrayList<String> listSelectedImg = new ArrayList<String>();
		for (FileInfo info : mlistSelectedFile) {
			listSelectedImg.add(info.mFilePathOrName);
		}

		Intent intent = new Intent();
		intent.putStringArrayListExtra("SELECTED_IMG", listSelectedImg);
		setResult(RESULT_OK, intent);
		finish();
	}

	/**
	 * 判断是不是无效的，是否可以继续执行（之前未选中情况下，该图片过大；或者选中数已达上限）
	 * 
	 * <br>Created 2014-9-22 下午1:49:09
	 * @param image 图片文件
	 * @param isSelect 之前是否选中
	 * @return boolean true表示无效；false表示有效的，可以继续执行
	 * @author       huangszh
	 * @param isSelect 
	 */
	private boolean isInValid(File image, boolean isSelect){
		// 之前已选中，不用判断了，继续执行取消选中
		if(isSelect){
			return false;
		}
		if (mMaxSelectCount <= mlistSelectedFile.size()) {
			// 选中数量已经达到上限了，直接提示，中断执行
			ToastUtils.display(LocalAlbumMultiSelect.this,
					R.string.tweet_upload_images_limit);
			return true;
		} else if(mIsLimitImageSize && image.length() > mMaxImageSize){
			// 需要判断图片大小且图片大小超过最大限制情况下，直接提示，中断执行
			ToastUtils.display(LocalAlbumMultiSelect.this,mLimitImageSizeHintId);
			return true;
		} else {
			return false;
		}
		
	}
	class HeadGridViewAdapter extends BaseAdapter {
		private boolean[] mSelectState;

		public void initSelectState() {
			if (null == mListRecent) {
				return;
			}

			int iSize = mListRecent.size();
			mSelectState = new boolean[iSize];

			for (int iIndex = 0; iIndex < mListRecent.size(); iIndex++) {
				for (FileInfo info : mlistSelectedFile) {
					if (info.mFilePathOrName.equalsIgnoreCase(mListRecent
							.get(iIndex).mFilePathOrName)) {
						mSelectState[iIndex] = true;
						break;
					}
				}
			}
		}

		public void setSelect(int position) {
			if (null == mSelectState || position < 1
					|| position  >= mSelectState.length) {
				return;
			}
	
			File fImage = new File(mListRecent.get(position).mFilePathOrName);
			if (!fImage.exists()) {
				Toast.makeText(LocalAlbumMultiSelect.this,
						R.string.pic_is_deleted, Toast.LENGTH_SHORT).show();
				return;
			}
			boolean isSelect = mSelectState[position];
			// 判断是否正常图片或者是否达到上限
			if (isInValid(fImage,isSelect)) {
				return;
			} 
			
			Holder holder = (Holder) (mMapRecent.get(position)).getTag();
			if (null != holder) {
				mSelectState[position] = !isSelect;
				if (mSelectState[position]) {
					holder.ivMask.setVisibility(View.VISIBLE);
					holder.ivClicked.setVisibility(View.VISIBLE);
					mlistSelectedFile.add(mListRecent.get(position));
					addFootPhoto(mListRecent.get(position).mFilePathOrName);
				} else {
					holder.ivMask.setVisibility(View.GONE);
					holder.ivClicked.setVisibility(View.GONE);
					removeSeletedImg(mListRecent.get(position).mFilePathOrName);
					delFootPhoto(mListRecent.get(position).mFilePathOrName);
				}
				

			}
		}

		@Override
		public int getCount() {
		    int count = mListRecent.size();
			if (count == 0) {
				return 1;
			}
			return count;
		}

		@Override
		public Object getItem(int position) {
			if (mListRecent != null && position < mListRecent.size()) {
				return mListRecent.get(position);
			}
			return null;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		class Holder {
			ImageView ivRecentItem;
			ImageView ivMask;
			ImageView ivClicked;
		}

		@SuppressLint("InflateParams")
        @Override
		public View getView(int position, View convertView, ViewGroup parent) {
			Holder holder = null;
			if (convertView != null && 0 != position) {
				holder = (Holder) convertView.getTag();
				// mMapRecent.remove(position);
			} else {
				LayoutInflater inflate = LayoutInflater
						.from(LocalAlbumMultiSelect.this);
				convertView = inflate
						.inflate(R.layout.local_album_recent, null);
				holder = new Holder();
				holder.ivRecentItem = (ImageView) convertView
						.findViewById(R.id.iv_img);
				holder.ivMask = (ImageView) convertView
						.findViewById(R.id.iv_selected_mask);
				holder.ivClicked = (ImageView) convertView
						.findViewById(R.id.iv_clicked_to_select);
				convertView.setTag(holder);
			}

			if (0 == position) {
				// 第一个显示拍照按钮
				holder.ivRecentItem
						.setBackgroundResource(R.drawable.take_photo);

			} else if (position < mListRecent.size()) {
				// 加载其他图片
				ImageLoader.getInstance().displayImage(
				        FileUtils.LOCAL_FILE_PREFIX + mListRecent.get(position).mFilePathOrName,
						holder.ivRecentItem,
						mAvoidOOMOptions,
						null);
				// mImgFetcher.loadImage(mListRecent.get(position),
				// holder.ivRecentItem);
			}

			if (null != mSelectState && position > 0
					&& mSelectState.length > position) {
				if (mSelectState[position]) {
					holder.ivMask.setVisibility(View.VISIBLE);
					holder.ivClicked.setVisibility(View.VISIBLE);
				} else {
					holder.ivMask.setVisibility(View.GONE);
					holder.ivClicked.setVisibility(View.GONE);
				}
			}

			mMapRecent.put(position, convertView);

			return convertView;
		}
	}

	public class AlbumListAdapter extends BaseAdapter {
		private LayoutInflater mInflater;
		private boolean mbDisplay = true;

		public AlbumListAdapter(Context context) {
			this.mInflater = LayoutInflater.from(context);
		}

		public void setDisplay(boolean bDispaly) {
			mbDisplay = bDispaly;
		}

		@Override
		public int getCount() {
			if (null == mListAlbum) {
				return 0;
			}
			return mListAlbum.size();
		}

		@Override
		public Object getItem(int arg0) {
			return null;
		}

		@Override
		public long getItemId(int arg0) {
			return 0;
		}

		public final class ViewHolder {
			public ImageView ivDemo;
			public TextView tvDirName;
		}

		@SuppressLint("InflateParams")
        @Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder = null;
			if (convertView == null) {
				holder = new ViewHolder();
				convertView = mInflater
						.inflate(R.layout.local_album_item, null);
				holder.ivDemo = (ImageView) convertView
						.findViewById(R.id.iv_demo);
				holder.tvDirName = (TextView) convertView
						.findViewById(R.id.tv_dir_name);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}

			if (null != mListAlbum && position < mListAlbum.size()) {
				SortedMediaFiles smf = mListAlbum.get(position);
				if (null != smf) {
					// 取出第一张显示
					FileInfo info = smf.getFirstFile();
					if (null != info) {
						holder.ivDemo.setBackgroundResource(0);
						if (mbDisplay) {
							ImageLoader.getInstance().displayImage(
							        FileUtils.LOCAL_FILE_PREFIX + info.mFilePathOrName,
									holder.ivDemo,
									mAvoidOOMOptions,
									null);
//							mImgFetcher.loadImage(info, holder.ivDemo);
						} else {
							holder.ivDemo.setImageBitmap(BitmapFactory
									.decodeResource(getResources(),
											R.drawable.local_image_default));
						}

					}

					holder.tvDirName.setText(smf.getDirName() + "("
							+ smf.getFilesCount() + ")");
				}
			}

			return convertView;
		}
	}

	class SelectMoreGridViewAdapter extends BaseAdapter {
		private boolean[] mSelectState;
		private boolean mbDisplay = true;

		public void initSelectState() {
			if (null == mListSelectMore) {
				return;
			}

			int iSize = mListSelectMore.size();
			mSelectState = new boolean[iSize];

			for (int iIndex = 0; iIndex < mListSelectMore.size(); iIndex++) {
				for (FileInfo info : mlistSelectedFile) {
					if (info.mFilePathOrName.equalsIgnoreCase(mListSelectMore
							.get(iIndex).mFilePathOrName)) {
						mSelectState[iIndex] = true;
						break;
					}
				}
			}
		}

		public void setDisplay(boolean bDispaly) {
			mbDisplay = bDispaly;
		}

		@Override
		public int getCount() {
			if (null == mListSelectMore) {
				return 0;
			}
			return mListSelectMore.size();
		}

		@Override
		public Object getItem(int position) {
			if (mListSelectMore != null && position < mListSelectMore.size()) {
				return mListSelectMore.get(position);
			}
			return null;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		class Holder {
			ImageView ivMoreItems;
			ImageView ivSelectedMask;
			ImageView ivClicked;
		}

		public void setSelect(int position) {
			if (null == mSelectState || position < 0
					|| position >= mSelectState.length) {
				return;
			}

			String strPath = mListSelectMore.get(position).mFilePathOrName;
			File fImage = new File(strPath);
			if (!fImage.exists()) {
				Toast.makeText(LocalAlbumMultiSelect.this,
						R.string.pic_is_deleted, Toast.LENGTH_SHORT).show();
				return;
			}
			boolean isSelect = mSelectState[position];
			// 判断是否可以继续往下执行
			if (isInValid(fImage,isSelect)) {
				return;
			} 

			Holder holder = null;
			if (0 == position) {
				// pos为0不准确，这里直接从gridview取元素
				holder = (Holder) mGridViewSelectMore.getChildAt(0).getTag();
			} else {
				holder = (Holder) (mMapSelectMore.get(position)).getTag();
			}

			if (null != holder) {
			    mSelectState[position] = !isSelect;
				if (mSelectState[position]) {
					mlistSelectedFile.add(mListSelectMore.get(position));
					holder.ivSelectedMask.setVisibility(View.VISIBLE);
					holder.ivClicked.setVisibility(View.VISIBLE);
					addFootPhoto(mListSelectMore.get(position).mFilePathOrName);
				} else {
					removeSeletedImg(mListSelectMore.get(position).mFilePathOrName);
					holder.ivSelectedMask.setVisibility(View.GONE);
					holder.ivClicked.setVisibility(View.GONE);
					delFootPhoto(mListSelectMore.get(position).mFilePathOrName);
					
				}
			}
		}

		@SuppressLint("InflateParams")
        @Override
		public View getView(int position, View convertView, ViewGroup parent) {
			Holder holder = null;
			if (convertView != null) {
				holder = (Holder) convertView.getTag();
				mMapSelectMore.remove(position);
				holder.ivMoreItems.setImageBitmap(BitmapFactory.decodeResource(
						getResources(), R.drawable.local_image_default));
			} else {
				LayoutInflater inflate = LayoutInflater
						.from(LocalAlbumMultiSelect.this);
				convertView = inflate
						.inflate(R.layout.local_album_recent, null);
				holder = new Holder();
				holder.ivMoreItems = (ImageView) convertView
						.findViewById(R.id.iv_img);
				holder.ivSelectedMask = (ImageView) convertView
						.findViewById(R.id.iv_selected_mask);
				holder.ivClicked = (ImageView) convertView
						.findViewById(R.id.iv_clicked_to_select);
				holder.ivMoreItems.setImageBitmap(BitmapFactory.decodeResource(
						getResources(), R.drawable.local_image_default));
				convertView.setTag(holder);
			}

			if (null != mListSelectMore && position < mListSelectMore.size()) {
				if (mbDisplay) {
					ImageLoader.getInstance().displayImage(
							FileUtils.LOCAL_FILE_PREFIX + mListSelectMore.get(position).mFilePathOrName,
							holder.ivMoreItems,
							mAvoidOOMOptions,
							null);
//					mImgFetcher.loadImage(mListSelectMore.get(position),
//							holder.ivMoreItems);
				}

				if (null != mSelectState && position >= 0
						&& mSelectState.length > position) {
					if (mSelectState[position]) {
						holder.ivSelectedMask.setVisibility(View.VISIBLE);
						holder.ivClicked.setVisibility(View.VISIBLE);
					} else {
						holder.ivSelectedMask.setVisibility(View.GONE);
						holder.ivClicked.setVisibility(View.GONE);
					}
				}
				
            }
			mMapSelectMore.put(position, convertView);

			return convertView;
		}
	}

	/**
	 * 销毁
	 */
	public void onDestroy() {
//		mImgFetcher.clearCache();
		LocalImageController.getInstance().clearLocalMedia();
		super.onDestroy();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		boolean bFinish = true;
		switch (keyCode) {
		case KeyEvent.KEYCODE_BACK:
			bFinish = switchView();
			break;
		}

		if (bFinish) {
			return super.onKeyDown(keyCode, event);
		}
		return false;
	}

	public boolean switchView() {
		mListSelectMore.clear();
		if (View.VISIBLE == mLayoutSelectMore.getVisibility()) {
			// 从文件夹选择更多中返回
			mLayoutLocalAlubm.setVisibility(View.VISIBLE);
			mLayoutSelectMore.setVisibility(View.GONE);

			mHeadGridViewAdapter.initSelectState();
			mHeadGridViewAdapter.notifyDataSetChanged();
			m_alAdapter.setDisplay(true);

			setActivityTitle(getString(R.string.local_image_lib));
		} else if (View.GONE == mLayoutSelectMore.getVisibility()) {
			// 退出本地图片多选
			mlistSelectedFile.clear();
			finish();
			return true;
		}

		return false;
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View view, int position,
			long id) {
		int vid = arg0.getId();
		if (vid == R.id.grid_recent) {
			clickRecent(position);
		} else if (vid == R.id.lv_local_album) {
			clickToSelectMore(position);
		} else if (vid == R.id.grid_select_more) {
			mSelectMoreGridViewAdapter.setSelect(position);
		}
	}

	private void clickRecent(int position) {
		
		if (0 == position) {
			// 拍照
			try {
				// 拍照不可用的话,提示
				if(!mIsCameraEnable){
					ToastUtils.display(LocalAlbumMultiSelect.this,
							mCameraUnableHintId);
					return;
				}
				if (mMaxSelectCount == mlistSelectedFile.size()) {
					// 已经有9张并尝试再选
					ToastUtils.display(LocalAlbumMultiSelect.this,
							R.string.tweet_upload_images_limit);
					return;
				}
				mCameraFile = new File(getSotrePath());
				photoUri = Uri.fromFile(mCameraFile);

				Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
				intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
				intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);

				startActivityForResult(intent, 0);
			} catch (Exception e) {
				Log.v(TAG, e.getMessage());
			}
		} else {
			mHeadGridViewAdapter.setSelect(position);
		}
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == 0) {
			if (photoUri == null)
				return;
			try {
				if (mCameraFile.exists()) {
					Intent intent = new Intent(
							Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
					Uri uri = Uri.fromFile(mCameraFile);
					intent.setData(uri);
					sendBroadcast(intent);

					FileInfo info = new FileInfo();
					info.mFilePathOrName = mCameraFile.getAbsolutePath();
					mlistSelectedFile.add(info);

					doFinish();
				}
			} catch (Exception localException) {
				localException.printStackTrace();
				return;
			}
		}
	}

	private String getSotrePath() {
		Time t = new Time();
		t.setToNow();

		String strDir = Environment.getExternalStorageDirectory()
				.getAbsolutePath() + "/DCIM/Camera/";
		File dir = new File(strDir);
		if (!dir.isDirectory()) {
			dir.mkdirs();
		}

		String strPath = strDir + "IMG_" + t.format("%Y%m%d_%H%M%S") + ".jpg";
		return strPath;
	}

	private void clickToSelectMore(int iPos) {
		int iSize = mListAlbum.size() + 1; // 因为加了头部
		if (iPos < 0 || iPos + 1 > iSize) {
			return;
		}

		SortedMediaFiles smf = mListAlbum.get(iPos - 1);
		if (null == smf) {
			return;
		}

		setActivityTitle(smf.getDirName());
		mLeftBtn.setVisibility(View.VISIBLE);

		mLayoutLocalAlubm.setVisibility(View.GONE);
		mLayoutSelectMore.setVisibility(View.VISIBLE);

		mListSelectMore.clear();
		List<FileInfo> listFI = smf.getFilesList();
		if (null != listFI) {
			for (FileInfo fi : listFI) {
				mListSelectMore.add(fi);
			}
		}

		mSelectMoreGridViewAdapter.initSelectState();
		mSelectMoreGridViewAdapter.setDisplay(true);
		mSelectMoreGridViewAdapter.notifyDataSetChanged();
	}

	private OnScrollListener scrollListener = new AbsListView.OnScrollListener() {

		@Override
		public void onScroll(AbsListView view, int firstVisibleItem,
				int visibleItemCount, int totalItemCount) {
		}

		@Override
		public void onScrollStateChanged(AbsListView view, int scrollState) {
//			if (0 == scrollState) {
//				if (View.VISIBLE == mLayoutSelectMore.getVisibility()) {
//					mSelectMoreGridViewAdapter.setDisplay(true);
//					mSelectMoreGridViewAdapter.notifyDataSetChanged();
//				} else if (View.GONE == mLayoutSelectMore.getVisibility()) {
//					m_alAdapter.setDisplay(true);
//					m_alAdapter.notifyDataSetChanged();
//				}
//			} else {
//				m_alAdapter.setDisplay(false);
//				mSelectMoreGridViewAdapter.setDisplay(false);
//			}
		}
	};

	// 取数据库失败时，启服务去搜两层
	private void startServiceToSearch() {
		boolean bSDCardExist = android.os.Environment.getExternalStorageState()
				.equals(android.os.Environment.MEDIA_MOUNTED);
		if (bSDCardExist) {
			if (isServiceRunning(this, ImageSearchService.class.getName())) {
			} else if (null == mIntentService) {
				mIntentService = new Intent(this, ImageSearchService.class);
				startService(mIntentService);
			} else {
				startService(mIntentService);
			}
		} else {
			Toast.makeText(this, R.string.no_sd_card, Toast.LENGTH_LONG).show();
		}
	}

	@Override
	protected void onStart() {
		ProgressTask task = new ProgressTask(this, R.string.loading) {
			// 取得文件的文件夹路径
			public String getImageDirName(String strPath) {
				int iPos = strPath.lastIndexOf('/');
				return strPath.substring(0, iPos + 1);
			}

			@Override
			protected void doSuccess() {
				LocalImageController.getInstance().notifyObservers();
			}

			@Override
			protected void doFail(int result) {
				startServiceToSearch();
			}

			@Override
			protected Integer doInBackground(Void... arg0) {
				Cursor cursor=null;
				try {
					mmapAlbumList.clear();
					String[] projection = new String[] {
							MediaStore.Images.ImageColumns._ID,
							MediaStore.Images.ImageColumns.DATA,
							MediaStore.Images.ImageColumns.DATE_TAKEN };

					ContentResolver cr = getContentResolver();
					cursor = cr.query(
							MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
							projection, null, null, null);
					if (null != cursor) {
						while (cursor.moveToNext()) {
							long lID = cursor
									.getLong(cursor
											.getColumnIndex(MediaStore.Images.ImageColumns._ID));
							String strImagePath = cursor
									.getString(cursor
											.getColumnIndex(MediaStore.Images.ImageColumns.DATA));
							long lDateTaken = cursor
									.getLong(cursor
											.getColumnIndex(MediaStore.Images.ImageColumns.DATE_TAKEN));

							String strImageDir = getImageDirName(strImagePath);
							if (!mmapAlbumList.containsKey(strImageDir)) {
								// 无此文件夹则创建
								File dir = new File(strImageDir);
								if (!dir.isDirectory()
										|| -1 != strImageDir.indexOf("/.")) {
									continue;
								}

								FileInfo dirInfo = new FileInfo();
								dirInfo.mFilePathOrName = dir.getAbsolutePath();

								SortedMediaFiles smf = new SortedMediaFiles();
								smf.mDirInfo = dirInfo;

								mmapAlbumList.put(strImageDir, smf);
							}

							SortedMediaFiles smf = mmapAlbumList
									.get(strImageDir);
							if (null != smf) {
								FileInfo fi = new FileInfo();
								fi.mFilePathOrName = strImagePath;
								fi.mLastModified = lDateTaken;
								fi.mID = lID;

								// 更新最后更新时间
								smf.mDirInfo.mLastModified = Math.max(
										lDateTaken, smf.mDirInfo.mLastModified);
								
								smf.addFile(fi);
							}
						}
						
					}

					LocalImageController.getInstance().clearLocalMedia();
					@SuppressWarnings("rawtypes")
					Iterator iter = mmapAlbumList.entrySet().iterator();
					while (iter.hasNext()) {
						@SuppressWarnings("rawtypes")
						Map.Entry entry = (Map.Entry) iter.next();
						LocalImageController.getInstance().addMediaFile(
								(SortedMediaFiles) entry.getValue());
					}
					return 0;
				} catch (Exception e) {
					return 1;
				} finally{
					if (cursor!=null){
						cursor.close();
					}					
				}
			}
		};
		task.execute();
		super.onStart();
	}
	
	/**
	 * 用来判断服务是否运行.
	 * 
	 * @param context
	 * @param className
	 *            判断的服务名字
	 * @return true 在运行 false 不在运行
	 */
	public static boolean isServiceRunning(Context mContext, String className) {
		boolean isRunning = false;
		ActivityManager activityManager = (ActivityManager) mContext
				.getSystemService(Context.ACTIVITY_SERVICE);
		List<ActivityManager.RunningServiceInfo> serviceList = activityManager
				.getRunningServices(30);
		if (!(serviceList.size() > 0)) {
			return false;
		}
		for (int i = 0; i < serviceList.size(); i++) {
			if (serviceList.get(i).service.getClassName().equals(className) == true) {
				isRunning = true;
				break;
			}
		}
		return isRunning;
	}

	// 将选中的图片移除
	private void removeSeletedImg(String strPath) {
		for (FileInfo info : mlistSelectedFile) {
			if (0 == info.mFilePathOrName.compareToIgnoreCase(strPath)) {
				mlistSelectedFile.remove(info);
				return;
			}
		}
	}
}